import pymongo
import common.gyblog as log

LOG = log.get_logger()

CONNECTION_STR = 'mongodb://192.168.0.196:27017/?readPreference=primary&appname=MongoDB%20Compass%20Community&ssl=false'
DATA_BASE = 'movies_record'  # 数据库名
DB_COL = 'javbook'  # 表名

# 查询条件，空表示全查询
SERIES = '1pondo'
YEAR = '2022'


def query_by_series_and_year(series, year):
    # 连接数据库
    db_client = pymongo.MongoClient(CONNECTION_STR)
    db_database = db_client[DATA_BASE]
    db_col = db_database[DB_COL]

    projection = {'_id': 0}
    # 查询
    if series == '':
        if year == '':
            query = {}
            query_ans = list(db_col.find(query, projection))
        else:
            query = {'year': year}
            query_ans = list(db_col.find(query, projection))
    else:
        if year == '':
            query = {'series': series}
            query_ans = list(db_col.find(query, projection))
        else:
            query = {'year': year, 'series': series}
            query_ans = list(db_col.find(query, projection))
    print(len(query_ans))

    db_client.close()
    return query_ans


def find_no_tor(query_ans):
    find_ans = []
    for q in query_ans:
        if q['tor'] == '':
            find_ans.append(q)
            print(q)
    print('共有{}个没有tor'.format(len(find_ans)))
    return find_ans


def find_no_tor_name(query_ans):
    find_ans = []
    for q in query_ans:
        if q['tor_name'] == '':
            find_ans.append(q)
            print(q)
    print('共有{}个没有tor_name'.format(len(find_ans)))
    return find_ans


def print_tor(series, year):
    # 连接数据库
    db_client = pymongo.MongoClient(CONNECTION_STR)
    db_database = db_client[DATA_BASE]
    db_col = db_database[DB_COL]

    projection = {'_id': 0}
    query = {'year': year, 'series': series}
    query_ans = list(db_col.find(query, projection))

    db_client.close()
    no_tor = []
    print('查询到{}个tor'.format(len(query_ans)))
    for q in query_ans:
        if q['tor'] == '':
            no_tor.append(q)
        else:
            print(q['tor'])
    print('{}个没有tor:'.format(len(no_tor)))
    for n in no_tor:
        print(n['num'],n['detail_url'])



if __name__ == '__main__':
    print_tor(SERIES, YEAR)
